import request from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import { userApi } from './user'
import { authApi } from './auth'
import { roleApi } from './role'
import { permissionApi } from './permission'

// Dashboard统计数据类型
export interface DashboardStats {
  userCount: number
  roleCount: number
  permissionCount: number
  onlineCount: number
  userStats: {
    totalUsers: number
    activeUsers: number
    disabledUsers: number
    lockedUsers: number
    newUsersThisMonth: number
  }
  permissionStats: {
    totalPermissions: number
    enabledPermissions: number
    disabledPermissions: number
    operationPermissions: number
    resourcePermissions: number
    apiPermissions: number
  }
  systemInfo: {
    version: string
    environment: string
    tenantEnabled: boolean
  }
}

// 角色统计信息
export interface RoleStats {
  totalRoles: number
  activeRoles: number
  disabledRoles: number
}

// 权限统计信息
export interface PermissionStats {
  totalPermissions: number
  enabledPermissions: number
  disabledPermissions: number
  operationPermissions: number
  resourcePermissions: number
  apiPermissions: number
}

// Dashboard API
export const dashboardApi = {
  // 获取登录趋势数据
  getLoginTrend: (): Promise<ApiResponse<{
    dates: string[]
    loginCounts: number[]
    uniqueUsers: number[]
  }>> => {
    return request.get('/dashboard/login-trend')
  },

  // 获取权限分布数据
  getPermissionDistribution: (): Promise<ApiResponse<{
    items: Array<{
      name: string
      value: number
    }>
    total: number
  }>> => {
    return request.get('/dashboard/permission-distribution')
  },

  // 获取系统信息
  getSystemInfo: (): Promise<ApiResponse<{
    version: string
    environment: string
    javaVersion: string
    osName: string
    osVersion: string
    totalMemory: string
    usedMemory: string
    freeMemory: string
    memoryUsage: string
    startTime: string
    uptime: string
    tenantEnabled: boolean
    databaseInfo: string
  }>> => {
    return request.get('/dashboard/system-info')
  },

  // 获取综合Dashboard数据（组合多个接口）
  getDashboardData: async (): Promise<DashboardStats> => {
    try {
      // 并行调用多个API
      const [
        userStatsRes,
        onlineCountRes,
        roleStatsRes,
        permissionStatsRes
      ] = await Promise.allSettled([
        userApi.getUserStatistics(),
        authApi.getOnlineUserCount(),
        roleApi.getRoleStatistics(),
        permissionApi.getPermissionStatistics()
      ])

      // 处理结果，提供默认值
      const userStats = userStatsRes.status === 'fulfilled' 
        ? userStatsRes.value.data 
        : {
            totalUsers: 0,
            activeUsers: 0, 
            disabledUsers: 0,
            lockedUsers: 0,
            newUsersThisMonth: 0
          }

      const onlineCount = onlineCountRes.status === 'fulfilled'
        ? onlineCountRes.value.data
        : 0

      const roleStats = roleStatsRes.status === 'fulfilled'
        ? roleStatsRes.value.data
        : { totalRoles: 0, enabledRoles: 0, disabledRoles: 0 }

      const permissionStats = permissionStatsRes.status === 'fulfilled'
        ? permissionStatsRes.value.data
        : {
            totalPermissions: 0,
            enabledPermissions: 0,
            disabledPermissions: 0,
            operationPermissions: 0,
            resourcePermissions: 0,
            apiPermissions: 0
          }

      return {
        userCount: userStats.totalUsers || 0,
        roleCount: roleStats.totalRoles || 0,
        permissionCount: permissionStats.totalPermissions || 0,
        onlineCount: onlineCount || 0,
        userStats,
        permissionStats,
        systemInfo: {
          version: '1.0.0',
          environment: import.meta.env.NODE_ENV || 'development',
          tenantEnabled: false // 从配置获取
        }
      }
    } catch (error) {
      console.error('获取Dashboard数据失败:', error)
      // 返回默认数据
      return {
        userCount: 0,
        roleCount: 0, 
        permissionCount: 0,
        onlineCount: 0,
        userStats: {
          totalUsers: 0,
          activeUsers: 0,
          disabledUsers: 0,
          lockedUsers: 0,
          newUsersThisMonth: 0
        },
        permissionStats: {
          totalPermissions: 0,
          enabledPermissions: 0,
          disabledPermissions: 0,
          operationPermissions: 0,
          resourcePermissions: 0,
          apiPermissions: 0
        },
        systemInfo: {
          version: '1.0.0',
          environment: 'development',
          tenantEnabled: false
        }
      }
    }
  }
}

export default dashboardApi
